﻿/*******************************************************************************
 * Copyright © 2016 李华丽 版权所有
 * Author: 李华丽
 * Description: 李华丽-快速开发平台
 * Website：http://www.cnblogs.com/lihuali
*********************************************************************************/
using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;

namespace Dotnet.Data
{
    public class DotnetDbContext : DbContext
    {
        private string DotnetDbContextMapping = System.Configuration.ConfigurationManager.AppSettings["DbMapping"];
        private static string ConnString = Environment.CurrentDirectory + "\\Database\\data.db";
        public DotnetDbContext()
            : base("DotnetDbContext")
        {
            this.Configuration.AutoDetectChangesEnabled = false;
            this.Configuration.ValidateOnSaveEnabled = false;
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }
        public DotnetDbContext(DbConnection conn):base(conn,true)
        {
            this.Configuration.AutoDetectChangesEnabled = false;
            this.Configuration.ValidateOnSaveEnabled = false;
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string assembleFileName = "";
            try
            {
                 assembleFileName =
                    Assembly.GetExecutingAssembly()
                        .CodeBase.Replace("Dotnet.Data.DLL", DotnetDbContextMapping)
                        .Replace("file:///", "");
                Assembly asm = Assembly.LoadFile(assembleFileName);
                var typesToRegister = asm.GetTypes()
                    .Where(type => !String.IsNullOrEmpty(type.Namespace))
                    .Where(
                        type =>
                            type.BaseType != null && type.BaseType.IsGenericType &&
                            type.BaseType.GetGenericTypeDefinition() == typeof (EntityTypeConfiguration<>));
                foreach (var type in typesToRegister)
                {
                    dynamic configurationInstance = Activator.CreateInstance(type);
                    modelBuilder.Configurations.Add(configurationInstance);
                }
                base.OnModelCreating(modelBuilder);
            }
            catch (Exception ex)
            {
#if DEBUG
                throw new Exception(ex.Message+"描述："+assembleFileName);
#endif
            }

        }
    }
}
